package com.example.wmuqrreader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class InspectionActivity extends Activity {

	DatabaseHandler db;
	
	Button 		button_save; 
	Button 		button_clear; 
	
	Spinner 	spinner;
	
	EditText	editText_qr;
	EditText	editText_sDate;
	EditText	editText_notes;
	EditText	editText_name;
	
	CheckBox	check_ok;
	CheckBox	check_clean;
	CheckBox	check_tie;
	CheckBox	check_recharge;
	CheckBox	check_mount;
	
	int			inspection_qr;
	
	Bundle 		extras;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inspection);
		
		
		db = new DatabaseHandler(this);
		
		button_save 	= (Button) findViewById(R.id.btn_save);
		button_clear 	= (Button) findViewById(R.id.btn_new);
		
		spinner 		= (Spinner) findViewById(R.id.spinner_inspectionList);
		
		editText_qr		= (EditText) findViewById(R.id.editText_qrNumber);
		editText_sDate	= (EditText) findViewById(R.id.editText_lastService);
		editText_notes	= (EditText) findViewById(R.id.editText_notes);
		editText_name	= (EditText) findViewById(R.id.editText_serviceInterval);
		
		check_ok		= (CheckBox) findViewById(R.id.checkBox_foundOk);
		check_clean		= (CheckBox) findViewById(R.id.checkBox_cleaned);
		check_tie		= (CheckBox) findViewById(R.id.checkBox_replacedTie);
		check_recharge	= (CheckBox) findViewById(R.id.checkBox_recharge);
		check_mount		= (CheckBox) findViewById(R.id.checkBox_mount);
		
		extras 			= getIntent().getExtras();
		
        //ID Passed - existing inventory
        if (extras.getString("ID") != null )
        {
        	inspection_qr = Integer.parseInt(extras.getString("ID"));
        	
        	populateFields(inspection_qr);
        	
            List<String> inspections = new ArrayList<String>();
            inspections = db.getAllInspectionDates(inspection_qr);
            
            // Creating adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, inspections);
     
            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     
            // attaching data adapter to spinner
            spinner.setAdapter(dataAdapter);
            
            if(inspections.size() < 1)
            {
            	SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
				editText_sDate.setText( sdf.format(new Date()) );
				
				spinner.setEnabled(false);
            }
        }
        else
        {
        	Toast.makeText(getApplicationContext(), "Cannot start an inspection entry without a valid QR", Toast.LENGTH_LONG).show();
        	finish();
        }
        
		//Add a function for the SAVE button click
        button_save.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				Inspection newIns = populateInspection(inspection_qr);
				
				if(newIns.get_svDate().length() > 0)
				{
					db.addInspection(newIns);
					Toast.makeText(getApplicationContext(), "Inspection created successfully", Toast.LENGTH_LONG).show();
					
					setResult(RESULT_OK, null);
					finish();
				}
				else
				{
					editText_sDate.setError( "A valid Service Date is required" ); 
				}				
			}
		});
        
        //Add a function for the CLEAR button click
        button_clear.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
				editText_sDate.setText( sdf.format(new Date()) );
				editText_notes.setText( "" );
				editText_name.setText( "" );
				
				check_ok.setChecked( false );
				check_clean.setChecked( false );
				check_tie.setChecked( false );
				check_recharge.setChecked( false );
				check_mount.setChecked( false );			
			}
		});
       	
        //Set SPINNER select listener
        spinner.setOnItemSelectedListener( new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
            {
            	//TODO: can't return to original...
            	if(position > 0)
            	{
            		Inspection entry = db.getInspection(inspection_qr, position);
            		
            		editText_sDate.setText( entry.get_svDate() );
        			editText_notes.setText( entry.get_otherNotes());
        			editText_name.setText( entry.get_officerName() );
        			
        			check_ok.setChecked( entry.is_foundOk() );
        			check_clean.setChecked( entry.is_cleaned() );
        			check_tie.setChecked( entry.is_replacedTie() );
        			check_recharge.setChecked( entry.is_recharged() );
        			check_mount.setChecked( entry.is_newMount() );
            	}
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) 
            {
                // your code here
            }

        });
		
	}
	
	//Populate the BuildingActivity fields from a given building
	private void populateFields(int inventory_id) {
		
		List<Inspection> allEntry = db.getAllInspection(inventory_id);		
				
		editText_qr.setText( Integer.toString(inventory_id) );
		
		if(allEntry.size() > 0)
		{
			Inspection entry = allEntry.get(0);
			
			editText_sDate.setText( entry.get_svDate() );
			editText_notes.setText( entry.get_otherNotes());
			editText_name.setText( entry.get_officerName() );
			
			check_ok.setChecked( entry.is_foundOk() );
			check_clean.setChecked( entry.is_cleaned() );
			check_tie.setChecked( entry.is_replacedTie() );
			check_recharge.setChecked( entry.is_recharged() );
			check_mount.setChecked( entry.is_newMount() );
		}
	}
	
	//Populate a new inspection object from field data
	private Inspection populateInspection(int id)
	{		

		boolean foundOk = check_ok.isChecked();
		boolean cl		= check_clean.isChecked();
		boolean rt		= check_tie.isChecked();
		boolean rc		= check_recharge.isChecked();
		boolean nm		= check_mount.isChecked();
		String notes	= editText_notes.getText().toString();
		String oN		= editText_name.getText().toString();
		String date		= editText_sDate.getText().toString();
		int qr			= id;
		
		
		return new Inspection(foundOk, cl, rt, rc, nm, notes, oN, date, qr);		
		
	}

}
